<template>
  <div>
    <router-link :to="{ name: 'Home' }">回到首页</router-link>

    <el-input v-model="title" placeholder="请输入" class="w500" @keyup.enter="handleAdd" />
    <el-button type="primary" @click="handleAdd">新增</el-button>
    <div>
      <p v-for="undoTodo in undoTodos" :key="undoTodo.id">
        <el-tag type="success" closable @close="handleRemove(undoTodo)">
          <span>{{ undoTodo.id }}-</span>
          <span>{{ undoTodo.title }}</span>
        </el-tag>
        <el-checkbox class="ml5" v-model="undoTodo.done"></el-checkbox>
      </p>
    </div>
    <div>
      <p>已完成</p>
      <p v-for="doneTodo in doneTodos" :key="doneTodo.id">
        <el-tag type="success">
          <span>{{ doneTodo.id }}-</span>
          <span>{{ doneTodo.title }}</span>
        </el-tag>
        <el-checkbox class="ml5" v-model="doneTodo.done"></el-checkbox>
      </p>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, computed, reactive, toRefs } from 'vue'
import { useStore } from 'vuex'

export default defineComponent({
  setup() {
    const store = useStore()
    const list = computed(() => store.state.todoList)
    const undoTodos = computed(() => list.value.filter((v) => !v.done))
    const doneTodos = computed(() => list.value.filter((v) => v.done))
    const state = reactive({
      title: '',
      dialogVisible: false
    })
    const handleAdd = () => {
      const { title } = state
      if (title) {
        // mock id
        const endTodo = list.value[list.value.length - 1]
        const id = endTodo?.id || 0
        store.dispatch('addTodo', { title, id: id + 1 })
        state.title = ''
      }
    }
    const handleRemove = ({ id }) => {
      store.dispatch('removeTodo', id)
    }
    return {
      ...toRefs(state),
      list,
      handleAdd,
      handleRemove,
      undoTodos,
      doneTodos
    }
  }
})
</script>
<style lang="scss" scoped>
.ml5 {
  margin-left: 5px;
}
</style>
